package com.example.demo.hot100;

/**
 * @Classname no10
 * @Description
 * @Date 2023/12/19 15:57
 * @Created by jyl
 * <p>
 * 回文链表
 * 判断一个链表是否为回文链表。
 *
 *  解：使用快慢指针找到链表的中点，然后反转链表的后半部分。最后，我们比较前半部分和反转后的后半部分是否相等。如果相等，说明链表是回文链表
 */
public class no8 {

    public static void main(String[] args) {
        PalindromeLinkedList solution = new PalindromeLinkedList();

        // 创建一个回文链表：1 -> 2 -> 3 -> 2 -> 1
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(1);

        // 判断链表是否为回文链表
        boolean result = solution.isPalindrome(head);

        // 输出结果
        System.out.println("Is palindrome: " + result);
    }


    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static class PalindromeLinkedList {

        public boolean isPalindrome(ListNode head) {
            // 使用快慢指针找到链表中点
            ListNode slow = head;
            ListNode fast = head;

            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }

            // 反转后半部分链表
            ListNode reversedHalf = reverseList(slow);

            // 比较前半部分和反转后的后半部分是否相等
            while (reversedHalf != null) {
                if (head.val != reversedHalf.val) {
                    return false;
                }
                head = head.next;
                reversedHalf = reversedHalf.next;
            }

            return true;
        }

        // 反转链表
        private static ListNode reverseList(ListNode head) {
            ListNode prev = null;
            ListNode current = head;

            while (current != null) {
                ListNode nextTemp = current.next;
                current.next = prev;
                prev = current;
                current = nextTemp;
            }

            return prev;
        }
    }
}
